<template>
  <a-card>
    <section class="filter-bar mb-16">
      <span class="label">字典项名称：</span>
      <a-input class="mr-24 w-300" allow-clear placeholder="请输入字典项名称" v-model="name" @pressEnter="search" />
      <a-button type="primary" @click="search">查询</a-button>
      <a-button class="ml-8" @click="reset">重置</a-button>
      <a-button
        v-if="$permissionJudge('DictCreate')"
        style="float: right"
        type="primary"
        icon="plus"
        @click="createOrEditData()"
        >新建
      </a-button>
    </section>
    <a-table row-key="id" :columns="columns" :data-source="data" :pagination="pagination">
      <template #categoryCode="val, data">
        <a-tooltip :title="val">
          <span class="overflow" style="max-width: 240px">
            {{ val }}
          </span>
        </a-tooltip>
      </template>
      <template #dictList="val, data">
        <template v-for="item in cloneDeep(val).slice(0, 5)">
          <a-tooltip :title="item.name">
            <a-tag class="overflow" style="max-width: 90px; vertical-align: middle" color="#108ee9">
              {{ item.name }}
            </a-tag>
          </a-tooltip>
        </template>
        <a v-if="val.length > 5" href="javascript:" class="ml-5 more" @click.stop="createOrEditData(data)">更多</a>
      </template>
      <template #action="val, data">
        <a v-if="$permissionJudge('DictUpdate')" @click.stop="createOrEditData(data)" href="javascript:">编辑</a>
        <a-divider type="vertical" />
        <a v-if="$permissionJudge('DictDelete')" @click.stop="delDictionary(data)" style="color: red" href="javascript:"
          >删除</a
        >
      </template>
    </a-table>
    <a-modal
      :maskClosable="false"
      :title="info.id ? '编辑字典项' : '新建字典项'"
      :width="650"
      :visible="showModal"
      :confirm-loading="confirmLoading"
      :ok-type="'primary'"
      @ok="confirmOk"
      @cancel="cancel"
    >
      <a-form :form="form">
        <a-form-item class="mb-15" label="字典名称" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input
            placeholder="请输入字典名称"
            v-decorator="['categoryName', { rules: [{ required: true, message: '请输入字典名称', whitespace: true }] }]"
            maxLength="30"
          ></a-input>
        </a-form-item>
        <a-form-item class="mb-15" label="字典值" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input
            placeholder="请输入字典值"
            v-decorator="['categoryCode', { rules: [{ required: true, message: '请输入字典值', whitespace: true }] }]"
            maxLength="30"
          ></a-input>
        </a-form-item>
        <section class="flex">
          <div class="ant-form-item-label ml-20">
            <label title="字典项值" class="ant-form-item-required">字典项值</label>
          </div>
          <section>
            <template v-if="info.dictList">
              <section class="cards-list" v-for="(item, index) in info.dictList">
                <a-form-item style="width: 220px" class="mb-10">
                  <a-input v-model="item.name" placeholder="请输入字典项名称" maxLength="30" />
                </a-form-item>
                <a-form-item style="width: 200px" class="ml-10 mb-10">
                  <a-input-number
                    style="width: 200px"
                    v-model="item.value"
                    placeholder="请输入字典项值"
                    maxLength="6"
                  />
                </a-form-item>
                <a href="javascript:" class="action" :class="{ 'disable-up-down': index === 0 }" @click="upData(index)">
                  <a-icon type="up-square" />
                </a>
                <a
                  href="javascript:"
                  class="action"
                  :class="{ 'disable-up-down': index === info.dictList.length - 1 }"
                  @click="downData(index)"
                >
                  <a-icon type="down-square" />
                </a>
                <a-popconfirm title="确定要删除吗？" ok-text="是" cancel-text="否" @confirm="removeDictList(index)">
                  <span class="text-red-700 action">
                    <a-icon type="minus-square" />
                  </span>
                </a-popconfirm>
              </section>
            </template>
            <a-button type="dashed" class="w500" @click="addDictList"> + 添加 </a-button>
          </section>
        </section>
      </a-form>
    </a-modal>
  </a-card>
</template>
<script>
import { tableMixins } from '@/utils/mixins'
import { getPageDictList, createDict, editDict, deleteDict } from '@/api/dictionaryData'
import { cloneDeep } from 'lodash'

export default {
  name: 'DictionaryData',
  mixins: [tableMixins],
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      showModal: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      loading: false,
      name: '',
      pageNum: 1,
      rowsNum: 10,
      columns: [
        { dataIndex: 'categoryName', title: '字典名称', width: 110 },
        { dataIndex: 'categoryCode', title: '字典值', scopedSlots: { customRender: 'categoryCode' }, width: 260 },
        { dataIndex: 'dictList', title: '字典项值', scopedSlots: { customRender: 'dictList' } },
        { align: 'center', title: '操作', scopedSlots: { customRender: 'action' }, width: 110 },
      ],
      data: [],
      info: {},
    }
  },
  created() {
    // if(!this.$permissionJudge('DictUpdate')&&!this.$permissionJudge('DictDelete')){
    //   this.columns = this.columns.filter(item=>item.title!=='操作')
    // }
    this.getData()
  },
  methods: {
    cloneDeep,
    upData(index) {
      if (index === 0) return false
      this.info = {
        ...this.info,
        dictList: this.swapArray(this.info.dictList, index - 1, index),
      }
    },
    downData(index) {
      if (index === this.info.dictList.length - 1) return false
      this.info = {
        ...this.info,
        dictList: this.swapArray(this.info.dictList, index, index + 1),
      }
    },
    swapArray(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      return arr
    },
    removeDictList(index) {
      this.info.dictList.splice(index, 1)
    },
    addDictList() {
      if (!this.info.dictList) this.info = { ...this.info, dictList: [] }
      this.info.dictList.push({
        value: '',
      })
    },
    cancel() {
      this.info = {}
      this.confirmLoading = false
      this.form.resetFields()
      this.showModal = false
    },
    confirmOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const { id, dictList: dictLists } = this.info
          const dictList =
            dictLists &&
            dictLists
              .filter((item) => item.value && item.name && item.name.trim())
              .map((item, index) => ({
                ...item,
                value: item.value * 1,
                name: item.name && item.name.trim(),
                sortNum: index + 1,
              }))
          if (!dictList || !dictList.length) return this.$message.warning('请添加字典项值')
          if (this.repetBankCards(dictList)) {
            this.$message.warning('字典项名称或字典项值重复！')
            this.confirmLoading = false
            return false
          }
          const { categoryName, categoryCode } = values
          this.confirmLoading = true
          const fun = id ? editDict : createDict
          fun({
            dictList,
            id,
            categoryCode: categoryCode && categoryCode.trim(),
            categoryName: categoryName && categoryName.trim(),
          })
            .then((res) => {
              this.$message.success(id ? '编辑成功！' : '新建成功！')
              this.search()
              this.cancel()
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    repetBankCards(data) {
      const dataIndex = []
      data.map((item) => {
        dataIndex.push(
          data
            .filter((l) => !(l.value === item.value && l.name === item.name))
            .some((l) => l.value === item.value || l.name === item.name)
        )
        return item
      })
      return dataIndex.some((item) => item)
    },
    createOrEditData(item) {
      if (item) {
        this.info = cloneDeep(item)
        this.$nextTick(() => {
          this.form.setFieldsValue({ categoryName: item.categoryName, categoryCode: item.categoryCode })
        })
      }
      this.showModal = true
    },
    delDictionary(data) {
      this.$confirm({
        title: '请确认删除数据字典',
        content: `请确认要删除【${data.categoryName}】数据字典?`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          if (this.confirmLoading) return false
          this.confirmLoading = true
          deleteDict([data.id])
            .then((res) => {
              this.$message.success('删除成功！')
              this.search()
            })
            .finally(() => {
              this.confirmLoading = false
            })
        },
      })
    },
    trenchSearch(e) {
      this.channelId = e
      this.search()
    },
    credentialsSearch(e) {
      this.credentialType = e
      this.search()
    },
    search() {
      this.pageNum = 1
      this.getData()
    },
    reset() {
      this.name = ''
      this.search()
    },
    getData() {
      this.loading = true
      const { name, pageNum, rowsNum } = this
      getPageDictList({
        name: name ? name.trim() : undefined,
        rowsNum,
        pageNum,
      })
        .then((res) => {
          this.loading = false
          const { items, rowCount } = res
          this.data = items
          this.total = rowCount
          this.total = rowCount
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>
<style lang="less" scoped>
.cards-list {
  display: flex;

  .action {
    padding-left: 10px;
    line-height: 38px;
    cursor: pointer;
  }

  .between-line {
    display: block;
    width: 30px;
    line-height: 35px;
    text-align: center;
  }
}

.w500 {
  margin-top: 5px;
  width: 500px;
}

.disable-up-down {
  color: #999;
  cursor: no-drop;
}
</style>
